<template>
  <div>
    <!-- 搜索框 -->
    <form action="/">
      <van-search
        v-model.trim="keyword"
        background="#0780d8"
        class="search-inp"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isShowResult = false"
      />
    </form>
    <!-- 搜索结果/历史/建议-->
    <component
      :keyword="keyword"
      :is="componentName"
      @update-keywords="onSearch"
    />
  </div>
</template>

<script>
import SearchHistory from './components/SearchHistory.vue'
import SearchSuggestions from './components/SearchSuggestions.vue'

import SearchResult from './components/SearchResult.vue'
import { mapMutations, mapState } from 'vuex'
export default {
  name: 'search',
  components: {
    SearchHistory,
    SearchSuggestions,
    SearchResult
  },
  props: {},
  data() {
    return {
      keyword: '',
      isShowResult: false
    }
  },
  methods: {
    ...mapMutations(['SET_HISTORIES']),
    onSearch(val) {
      // 1. 更新keyword
      this.keyword = val
      // 2.存到vuex
      let newHistories = [this.keyword, ...this.histories]
      // 3.去重 new Set
      newHistories = [...new Set(newHistories)]
      this.SET_HISTORIES(newHistories)
      this.isShowResult = false
      // 4. 监听输入框按下回车的值
      this.isShowResult = true
    },
    onCancel() {
      // this.$toast('取消')
      // 触发取消， 先清空keyword ,再触发onCance
      if (this.keyword === '') {
        // 返回上一页
        this.$router.go(-1)
      } else {
        this.this.keyword = ''
      }
    }
  },
  computed: {
    ...mapState(['histories']),
    componentName() {
      // 1.搜索框都没有实际内容的时候，渲染搜索历史
      if (this.keyword === '') {
        return 'SearchHistory'
      }
      // 2.keyword 一定有值
      // 要么渲染搜索建议，要么搜索结果
      // 把输入框按下回车的值 用来判断是否有值
      if (this.isShowResult) {
        return 'SearchResult'
      }
      return 'SearchSuggestions'
    }
  }
}
</script>

<style scoped lang="less">
.search-inp {
  .van-search__action {
    color: #fff;
  }
}
</style>
